<?php

declare(strict_types = 1);

namespace app\Traits;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

trait Export
{
    /**
     * 导出Excel表格 Xlsx格式(2007版)
     *
     * @param  array   $title  表头单元格内容
     * @param  array   $data   从第二行开始写入的数据
     * @param  string  $path   Excel文件保存位置,路径中的目录必须存在
     *
     * @return null 没有设定返回值
     * @author   liang <23426945@qq.com>
     * @datetime 2019-12-22
     *
     */
    protected function batchExcel($file_name, $title = [], $data = [], $path = PUBLIC_PATH . '/exports/')
    {
        $this->startExport($spreadsheet, $title, $data);

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

        $result = $writer->save($path . '/' . $file_name . '.xlsx');
        var_dump($result);


        // 释放内存
        // $spreadsheet->disconnectWorksheets();
    }

    protected function download($file_name = '', $title = [], $data = [])
    {
        $this->startExport($spreadsheet, $title, $data);

        if ( empty($file_name) ) {
            $file_name = '导出表格';
        }
        $file_name .= ' - ' . date('Ymdhis') . '.xlsx';
        // 文件名不可以出现空格，否则导出的表格无法打开
        $file_name = str_replace(' ', '', $file_name);

        header("Content-Type: text/csv");
//        header('Content-Type:application/vnd.ms-excel');
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;filename="' . $file_name . '"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
    }

    private function startExport(&$spreadsheet, $title = [], $data = []) : void
    {
        // 获取Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 表头单元格内容 第一行
        $titCol = 'A';
        foreach ($title as $value) {
            if ($value == 'password') continue;
            var_dump($titCol . '1', $value);
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }

        // 从第二行开始写入数据
        $row = 2;
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $key => $value) {
                var_dump($dataCol . $row);
                var_dump($key);
                var_dump($value);
                var_dump(PHP_EOL);
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $value);
                $dataCol++;
            }
            $row++;
        }
    }
}
